<template>
  <div class="card">
    <h3>运单</h3>
    <form @submit.prevent="create">
      <input v-model="form.trackingNumber" placeholder="运单号" required />
      <select v-model.number="form.orderId" required>
        <option value="" disabled>选择订单</option>
        <option v-for="o in orders" :key="o.id" :value="o.id">{{ o.orderNumber }} - {{ o.status }}</option>
      </select>
      <select v-model.number="form.carrierId" required>
        <option value="" disabled>选择承运商</option>
        <option v-for="c in carriers" :key="c.id" :value="c.id">{{ c.name }}</option>
      </select>
      <button type="submit">创建运单</button>
    </form>

    <table>
      <thead>
        <tr><th>ID</th><th>运单号</th><th>状态</th><th>订单</th><th>承运商</th><th>发货时间</th><th>到达时间</th><th></th></tr>
      </thead>
      <tbody>
        <tr v-for="s in list" :key="s.id">
          <td>{{ s.id }}</td>
          <td>{{ s.trackingNumber }}</td>
          <td>
            <select v-model="statusMap[s.id]" @change="updateStatus(s.id)">
              <option>CREATED</option>
              <option>IN_TRANSIT</option>
              <option>DELIVERED</option>
              <option>CANCELLED</option>
            </select>
          </td>
          <td>{{ s.order.orderNumber }}</td>
          <td>{{ s.carrier.name }}</td>
          <td>{{ s.shippedAt?.slice(0,19).replace('T',' ') }}</td>
          <td>{{ s.deliveredAt ? s.deliveredAt.slice(0,19).replace('T',' ') : '-' }}</td>
          <td></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { api, type Carrier, type CustomerOrder, type Shipment } from '../lib/api'

const list = ref<Shipment[]>([])
const orders = ref<CustomerOrder[]>([])
const carriers = ref<Carrier[]>([])
const statusMap = reactive<Record<number, Shipment['status']>>({})

const form = reactive<{ trackingNumber: string; orderId: number | ''; carrierId: number | '' }>({ trackingNumber: '', orderId: '', carrierId: '' })

async function load() {
  const [s, o] = await Promise.all([
    api.get<Shipment[]>('/shipments'),
    api.get<CustomerOrder[]>('/orders')
  ])
  list.value = s.data
  orders.value = o.data
  // 沿用示例承运商列表（从订单和运单中提取），也可以在后端创建 CarrierController 暴露列表
  const carrierMap: Record<number, Carrier> = {}
  for (const ship of list.value) carrierMap[ship.carrier.id] = ship.carrier
  carriers.value = Object.values(carrierMap)
  for (const ship of list.value) statusMap[ship.id] = ship.status
}

async function create() {
  if (!form.orderId || !form.carrierId) return
  await api.post('/shipments', form)
  form.trackingNumber=''; form.orderId=''; form.carrierId=''
  await load()
}

async function updateStatus(id: number) { await api.patch(`/shipments/${id}/status`, null, { params: { status: statusMap[id] } }); await load() }

onMounted(load)
</script>


